/**
 * File    : Setup.java
 * Created : 2008-9-5
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.tutorial;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.providers.encoding.PasswordEncoder;

import com.luhuiguo.sso.tutorial.entity.Role;
import com.luhuiguo.sso.tutorial.entity.User;
import com.luhuiguo.sso.tutorial.services.UserService;

/**
 * @author LuHuiguo
 * @version $Id: Setup.java 2 2008-10-04 13:04:21Z LuHuiguo $
 * 
 */
public class Setup {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(Setup.class);

	/**
	 * The UserService
	 */
	private UserService userService;

	private List<User> users;

	private List<Role> roles;

	private PasswordEncoder passwordEncoder;

	public void run() {
		if (logger.isDebugEnabled()) {
			logger.debug("Initializing data ... ");
		}

		if (userService.getAllRole(0, 1).size() == 0) {
			for (Role role : roles) {
				try {
					userService.createRole(role);
					if (logger.isDebugEnabled()) {
						logger.debug("Create role: " + role.getName());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (userService.getAllUser(0, 1).size() == 0) {
			for (User user : users) {
				user.setPassword(passwordEncoder.encodePassword(user
						.getPassword(), null));
				try {
					userService.createUser(user);
					if (logger.isDebugEnabled()) {
						logger.debug("Create user: " + user.getName());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Data initialization complete [OK]");
		}
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * @param users
	 *            the users to set
	 */
	public void setUsers(List<User> users) {
		this.users = users;
	}

	/**
	 * @param roles
	 *            the roles to set
	 */
	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	/**
	 * @param passwordEncoder
	 *            the passwordEncoder to set
	 */
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

}
